﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RiskMan.Config;
using RiskMan.DataClass.Models.Quik;
using RiskMan.Models;
using System.Windows.Forms;
using RiskMan.Views.Dialogs;
using System.Reflection;
using System.Collections.ObjectModel;
using RiskMan.DataClass.Models;
using System.Windows.Threading;

namespace WpfApplication1.Providers
{
    class DDEChannelCurrentList : XlDde.XlDdeChannel
    {
        private ObservableCollection<CurrentParamModel> _observableCollection;

        public DDEChannelCurrentList()
        {

        }

        protected override void ProcessTable(XlDde.XlTable xt, string topic)
        {

            _observableCollection = RiskMan.MainWindow.StaticRiskMan._dataProvider.CurrentList;
            try
            {
                for (int i = 0; i < xt.Rows; i++)
                {
                    CurrentParamModel cpm = new CurrentParamModel();
                    List<String> names = new List<String>();

                    for (int j = 0; j < xt.Columns; j++)
                    {
                        xt.ReadValue();
                        if (Namespace.Count == 0 && i == 0)
                        {
                            cpm = null;
                            names.Add(xt.StringValue);
                        }
                        else
                        {
                            if (IsSend(xt) == true)
                            {
                                try
                                {
                                    if (Namespace[j] == "CLASS_CODE") cpm.ClassCode = Convert.ToString(xt.GetValue());
                                    if (Namespace[j] == "CODE") cpm.Seccode = Convert.ToString(xt.GetValue());
                                    if (Namespace[j] == "last") cpm.LastPrice = Convert.ToDouble(xt.GetValue());
                                    if (Namespace[j] == "SEC_PRICE_STEP") cpm.StepPrice = Convert.ToDouble(xt.GetValue());
                                    if (Namespace[j] == "SEC_SCALE") cpm.Accurasy = Convert.ToInt32(xt.GetValue());
                                    if (Namespace[j] == "lotsize") cpm.Quantity = Convert.ToInt32(xt.GetValue());
                                    if (Namespace[j] == "pricemax") cpm.MaxPrice = Convert.ToDouble(xt.GetValue());
                                    if (Namespace[j] == "pricemin") cpm.MinPrice = Convert.ToDouble(xt.GetValue());
                                    if (Namespace[j] == "prevprice") cpm.ClosePrice = Convert.ToDouble(xt.GetValue());
                                    if (Namespace[j] == "selldepo") cpm.GoSell = Convert.ToDouble(xt.GetValue());
                                    if (Namespace[j] == "buydepo") cpm.GoBuy = Convert.ToDouble(xt.GetValue());
                                    if (Namespace[j] == "steppricet") cpm.StepPricet = Convert.ToDouble(xt.GetValue());
                                }
                                catch (ArgumentOutOfRangeException)
                                {
                                    string message = "\"Текущая таблица параметров\" в разных терминалах настроены по разному. \n\r" +
                                        "Для правильной настройки таблице ознакомьтесь с инструкцией." +
                                        "\n\rНеобходимо чтоб название и количество выводимых параметров совпадало.";
                                    string title = "Ошибка";
                                    if (base.IsShowMessage == false)
                                    {
                                        base.IsShowMessage = true;
                                        new DialogMessage(message, title);
                                    }
                                    cfg.SetLog(message, RiskMan.MainWindow.StaticRiskMan.ListBox_Logs, GetType(), MethodBase.GetCurrentMethod());

                                }
                                catch (Exception ex)
                                {
                                    new DialogMessage(ex.Message, "DDEChannelCurrentList");
                                }
                            }
                            else
                            {
                                cpm = null;
                            }
                        }
                    }
                    if (cpm != null)
                    {
                        bool tr = false;

                        for (int r = 0; r < _observableCollection.Count; r++)
                            if (_observableCollection[r].Seccode == cpm.Seccode)
                            {
                                tr = true;
                                int r1 = r;
                                Dispatcher.CurrentDispatcher.BeginInvoke(new Action(delegate()
                                {
                                    _observableCollection[r1].LastPrice = cpm.LastPrice;
                                    _observableCollection[r1].GoBuy = cpm.GoBuy;
                                    _observableCollection[r1].GoSell = cpm.GoSell;
                                }));


                                continue;
                            }

                        if (tr == false)
                            AddOptionDataModel(cpm);


                    }
                    if (names.Count > 0)
                        Namespace = new List<String>(names);
                }
            }
            catch (Exception ex)
            {
                new DialogOkCancel(ex.Message, "DDEChannelCurrentList");
            }
        }

        public override void Disconnected(bool isConnected)
        {
            Namespace.Clear();
            QuikIntegration.dde.QuikUtil.StartDDE();
        }

        public delegate void CurrentDataModelDelegate(CurrentParamModel dl);

        public void AddOptionDataModel(CurrentParamModel dl)
        {
            if (!RiskMan.MainWindow.StaticRiskMan._dataProvider.Dispatcher.CheckAccess())
            {
                RiskMan.MainWindow.StaticRiskMan._dataProvider.Dispatcher.BeginInvoke(
                    DispatcherPriority.Normal, new CurrentDataModelDelegate(AddOptionDataModel), dl
                );
                return;
            }

            _observableCollection.Add(dl);
        }
    }
}
